package com.socio.resources;

import java.util.List;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.socio.behaviors.DAOBehavior;
import com.socio.behaviors.UserUDIDBehavior;
import com.socio.model.ClientUser;
import com.socio.model.User;

@Path("/settings")
public class SettingsResource {

	@Path("/get")
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getSettings(@QueryParam("udid") String udid) {
		
		if(udid == null)
			return "";
		
		DAOBehavior userDAO = new UserUDIDBehavior();
		
		// get user with udid, create user if they aren't already in the db
		User user = null;
		Object result = userDAO.read(udid, null);
        List<Object> userList = (List<Object>)result;
        if(!userList.isEmpty() && userList.get(0) != null) {
        	user = (User)userList.get(0);
        } else {
        	user = new User();
        	user.setAndroidUDID(udid);
        	userDAO.create(user);
        }
        
        Gson gson = new Gson();
        return gson.toJson(user.getClientUser());
	}
	
	@Path("/post")
    @POST
    @Produces(MediaType.TEXT_PLAIN)
    @Consumes(MediaType.APPLICATION_JSON)
	public String postSettings(String json) {
		Boolean added = false;

		// parse json to get user
        User parsedUser;
        Gson gson = new Gson();
		try {
			parsedUser = new User(gson.fromJson(json, ClientUser.class));
		} catch(JsonSyntaxException jse) {
			return added.toString();
		}
		
		DAOBehavior userDAO = new UserUDIDBehavior();
		
		// match up parsed user with the one found in the database if there is one
		User user = null;
        Object result = userDAO.read(parsedUser.getAndroidUDID(), null);
        List<Object> userList = (List<Object>)result;
        if(!userList.isEmpty() && userList.size() == 1 && userList.get(0) != null) {
            user = (User)userList.get(0);
            user.setAndroidUDID(parsedUser.getAndroidUDID());
            user.setNickname(parsedUser.getNickname());
        } else {
        	user = parsedUser;
        }
        
        // persist
        added = userDAO.create(user);

        return added.toString();
	}
}
